package org.colafries.admin.querybuilder.customQuery;

import cn.hutool.core.collection.CollectionUtil;
import org.colafries.admin.entity.vo.CustomQueryReqVO;
import org.colafries.admin.querybuilder.entity.CustomQueryParamContext;
import org.colafries.admin.entity.domain.QueryParam;
import org.colafries.admin.querybuilder.entity.CustomQuerySqlBuildContext;

import java.util.*;

/**
 * @author colafries
 * @version v1.0
 * @ClassName SortPartBuilder
 * @Description
 * @date Created in 2024/5/15
 **/
public class CustomQuerySortBuilder implements CustomQuerySqlSegmentBuilder {
    /**
     * @param customQueryParam
     * @return void
     * @author colafries
     * @Date 2024/5/16
     */
    @Override
    public void buildQueryParma(CustomQueryReqVO.CustomQueryParam customQueryParam, CustomQueryParamContext customQueryParamContext) {
        //排序
        Optional.ofNullable(customQueryParam)
                .map(CustomQueryReqVO.CustomQueryParam::getSorts)
                .ifPresent(sorts -> sorts.forEach(sort -> {
                    Optional.ofNullable(customQueryParamContext.getDataModelConfigMap().get(sort.getSortFieldHash()))
                            .ifPresent(configRspVO -> customQueryParamContext.getSorts().add(QueryParam.Sort.builder()
                                    .field(configRspVO.getField())
                                    .fieldHash(sort.getSortFieldHash())
                                    .sortType(sort.getSortType())
                                    .defaultAggregator(configRspVO.getDefaultAggregator())
                                    .build())
                            );
                }));
    }

    /**
     * sortPart:orderByColumns
     *
     * @param queryParam
     * @param customQuerySqlQueryContext
     * @return void
     * @author colafries
     * @Date 2024/5/16
     */
    @Override
    public void buildQuery(QueryParam queryParam, CustomQuerySqlBuildContext customQuerySqlQueryContext) {
        // sort
        List<QueryParam.Sort> sorts = Optional.of(queryParam).map(QueryParam::getSorts).orElse(Collections.emptyList());

        sorts.forEach(sort -> {
            // 根据dimension.fieldHash 获取自定义表Column
            Optional.ofNullable(customQuerySqlQueryContext.getCustomTableSchemaMap().get(sort.getFieldHash())).ifPresent(customTableColumn -> {
                String tableHash = customTableColumn.getTableHash();
                String fieldHash = customTableColumn.getFieldHash();
                if (fieldHash.equals(sort.getFieldHash())) {
                    sort.setTableHash(tableHash);
                }
            });

        });

        //构建order by
        // e.g. order by col1 asc, SUM(col2) desc
        List<String> orderByList = new ArrayList<>();
        if (!CollectionUtil.isEmpty(sorts)) {
            // 构建order by 表达式，并添加到orderByList
            sorts.stream().map(sort -> {
                        String sortFieldExpression = customQuerySqlQueryContext.getColumnExpressionMap().get(sort.getFieldHash());
                        return String.format("%s %s", sortFieldExpression, sort.getSortType());
                    })
                    .forEach(orderByList::add);
        }
        customQuerySqlQueryContext.setOrderByColumns(orderByList);
    }
}
